﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace VersionComparer
{
    public partial class ListManagerControl<T> : UserControl
        where T: new()
    {
        public ListManagerControl()
        {
            InitializeComponent();
        }

        private void lstItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            propertyGrid1.SelectedObject = lstItems.SelectedItem;
        }

       

        private void mnuAdd_Click(object sender, EventArgs e)
        {
            try
            {
                T newValue = new T();
                 int index = lstItems.Items.Add(newValue );
                 lstItems.SelectedIndex = index;
            }
            catch ( Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

        private void mnuRemove_Click(object sender, EventArgs e)
        {
            if ( lstItems.SelectedIndex >= 0 )
                lstItems.Items.RemoveAt(lstItems.SelectedIndex);
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            mnuRemove.Enabled = lstItems.SelectedItem != null;
        }


        private void RefreshList(List<T> list)
        {
            lstItems.Items.Clear();
            if (list != null)
            {
                foreach (T listValue in list)
                {
                    lstItems.Items.Add(listValue);
                }

                if (list.Count > 0)
                    lstItems.SelectedIndex = 0;
            }
        }

        private List<T> ToList()
        {
            List<T> result = new List<T>();
            foreach (T listValue in lstItems.Items)
                result.Add(listValue);
            
            return result;
        }
        public List<T> List
        {
            get
            {
                return ToList();
            }
            set
            {
                Invoke((MethodInvoker)delegate()
                {
                    RefreshList(value);
                });
            }
        }

        private void propertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            lstItems.Refresh();
        }
        
    }
}
